package cn.micro.system.manage.annotate.impl;

import cn.micro.system.manage.annotate.UniqueMenu;
import cn.micro.system.manage.entity.SysDimMenu;
import cn.micro.system.manage.service.SysDimMenuService;

import javax.annotation.Resource;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.annotation.Annotation;
import java.util.function.Predicate;

public class MenuValidation<T extends Annotation> implements ConstraintValidator<T, SysDimMenu> {

    protected Predicate<SysDimMenu> predicate = c -> true;

    @Resource
    protected SysDimMenuService sysDimMenuService;

    @Override
    public boolean isValid(SysDimMenu sysDimMenu, ConstraintValidatorContext constraintValidatorContext) {
        return sysDimMenuService == null || predicate.test(sysDimMenu);
    }

    /**
     * 校验角色编码或者角色名称是否重复
     */
    public static class UniqueMenuValidate extends MenuValidation<UniqueMenu>{
        @Override
        public void initialize(UniqueMenu constraintAnnotation) {
            predicate = c -> sysDimMenuService.getByName(c).isEmpty();
        }
    }
}
